import { isNullOrUnDef } from '@/utils/is'
import type { Ref, ComputedRef } from 'vue';
import { unref } from 'vue'

interface UseFormValueContext {
  defaultFormModel: Ref<any>,
  formModel: any,
  schemas: any[]
}

export function useFormValue ({
  defaultFormModel,
  formModel,
  schemas
}: UseFormValueContext) {

  /**
   * 初始化组件的默认值
   */
  function initDefault() {
    const obj = {}
    schemas.forEach(item => {
      const { defaultValue } = item
      if(!isNullOrUnDef(defaultValue)) {
        obj[item.field] = defaultValue
        formModel[item.field] = defaultValue
      }
    })
    defaultFormModel.value = obj
  }

  /** 提交表单前处理表单值 */
  function handleSubmitFormValue() {
    Object.keys(formModel).forEach((key) => {
      // 删除空格
      formModel[key] = formModel[key].trim()
    })
  }

  return {
    initDefault,
    handleSubmitFormValue
  }
}